package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WxConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.wx.HttpClientSslUtils;
import com.ruoyi.common.utils.wx.WeChatUtil;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.domain.BdmUser;
import com.ruoyi.system.domain.vo.applet.AppletWxLoginVo;
import com.ruoyi.system.mapper.BdmUserMapper;
import com.ruoyi.system.service.IBdmUserService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IBdmUserService bdmUserService;

    @Autowired
    private BdmUserMapper bdmUserMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        // TODO 暂时去掉验证码
        //     validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 微信一键登录
     *
     * @param appletWxLoginVo
     * @return
     */
    @Transactional
    public AjaxResult loginOpenid(AppletWxLoginVo appletWxLoginVo) {
        AjaxResult ajax = AjaxResult.success();
        try {

            // 微信小程序ID
            String appid = WxConfig.APP_ID;
            // 微信小程序秘钥
            String secret = WxConfig.secret;

            // 根据小程序穿过来的code想这个url发送请求
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + appletWxLoginVo.getCode() + "&grant_type=authorization_code";
            // 发送请求，返回Json字符串
            String str = WeChatUtil.httpRequest(url, "GET", null);
            // 转成Json对象 获取openid
            JSONObject jsonObject = JSONObject.parseObject(str);
            // 我们需要的openid，在一个小程序中，openid是唯一的
            String openid = jsonObject.get("openid").toString();
            String sessionKey = jsonObject.get("session_key").toString();
            appletWxLoginVo.setSessionKey(sessionKey);
            SysUser sysUser = new SysUser();
            String password = "123456";
                String encryptPassword = SecurityUtils.encryptPassword(password);
            if (StringUtils.isNotEmpty(openid)) {
                String phoneNumber = this.getPhoneNumber(appletWxLoginVo);
                //用openId 判断是否存在
                BdmUser bdmUser = new BdmUser();
                bdmUser.setUserPhone(phoneNumber);
                List<BdmUser> bdmUserList = bdmUserService.selectBdmUserList(bdmUser);
                //用户不存在
                if (StringUtils.isEmpty(bdmUserList)) {
                    //保存用户信息
                    if (!userService.checkUserNameUnique(sysUser)) {
                        return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
                    } else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && !userService.checkPhoneUnique(sysUser)) {
                        return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
                    }
                    sysUser.setNickName(NameUtil.getName());
                    sysUser.setRoleId(2L);
                    sysUser.setUserName(phoneNumber);
                    sysUser.setPhonenumber(phoneNumber);
                    sysUser.setPassword(encryptPassword);
                    sysUser.setRemark("微信用户");
                    sysUser.setUserType("01");
                    ajax.put("nikeName",sysUser.getNickName());
                    ajax.put("avatar",sysUser.getAvatar());
                    userService.insertUser(sysUser);
                    //保存用户信息
                    bdmUser.setOpenId(openid);
                    bdmUser.setSysUserid(sysUser.getUserId());
//                    bdmUser.setParentId(appletWxLoginVo.getPromotionId());
                    bdmUser.setCreateTime(new Date());
                    bdmUser.setUserPhone(phoneNumber);
//                    bdmUser.setDistributionParentId(appletWxLoginVo.getPromotionId());
                    bdmUserMapper.insertBdmUser(bdmUser);
                } else {
                    BdmUser user = bdmUserList.get(0);
                    user.setOpenId(openid);
                    bdmUserService.updateBdmUser(user);
                    sysUser = userService.selectUserById(user.getSysUserid());
                    // 判断当前用户有无 父id
//                    if (StringUtils.isNotNull(appletWxLoginVo.getPromotionId())
//                            && StringUtils.isNull(user.getParentId())
//                            && !appletWxLoginVo.getPromotionId().equals(user.getSysUserid())) {
//                        BdmUser bUser = new BdmUser();
//                        bUser.setId(user.getId());
//                        bUser.setParentId(appletWxLoginVo.getPromotionId());
//                        bUser.setDistributionParentId(appletWxLoginVo.getPromotionId());
//                        bdmUserService.updateBdmUser(bUser);
//                        ajax.put("flag",false);
//                    }else {
//                       if (ObjectUtils.isNotEmpty(user.getParentId())){
//                           SysUser parentUser = userService.selectUserById(user.getParentId());
//                           ajax.put("parentNickName",parentUser.getNickName());
//                       }else{
//                           ajax.put("parentNickName","");
//                       }
//                        ajax.put("flag",true);
//
//                    }
                    ajax.put("nikeName",sysUser.getNickName());
                    ajax.put("avatar",sysUser.getAvatar());

                    //更新用户信息
                    //  ZyUser zyUserIsExist= zyUser;
//                    zyUser.setPhoneNumber(phoneNumber);
//                    zyUser.setUserName(phoneNumber);
//                    if(StringUtils.isEmpty(zyUser.getOpenId())){
//                        zyUser.setOpenId(openid);
//                    }
//                    zyUserService.updateZyUser(zyUser);
                }
                //用户存在
                if (appletWxLoginVo.getPromotionId() != null && sysUser.getUserId().equals(appletWxLoginVo.getPromotionId())){
                    throw new RuntimeException("自己不能扫自己的推广二维码");
                }
                if (appletWxLoginVo.getPromotionId() != null){
                    log.info("设置缓存的key是{},value是{}",sysUser.getUserId(),appletWxLoginVo.getPromotionId());
                    redisCache.setCacheObject(sysUser.getUserId().toString(), appletWxLoginVo.getPromotionId().toString());
                }
                String token = this.login2(sysUser.getUserName(), password);
                ajax.put(Constants.TOKEN, token);
                ajax.put("sessionKey",sessionKey);
                ajax.put("userId",sysUser.getUserId());
            }
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("登录失败，请联系管理员！");
        }
    }

    public String getPhoneNumber(AppletWxLoginVo getPhoneVo) throws Exception {

        //获取accessToken
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
                + "?access_token=" + accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", getPhoneVo.getPhoneCode());
        String reqJsonStr = JSONObject.toJSONString(jsonObject);
        JSONObject wxJson = JSON.parseObject(HttpClientSslUtils.doPost(url, reqJsonStr));
        String phone_info = wxJson.getString("phone_info");
        JSONObject phone_info1 = JSONObject.parseObject(phone_info);
        String phoneNumber = null;
        try {
            phoneNumber = phone_info1.getString("phoneNumber");
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("获取用户手机号失败！");
        }
        return phoneNumber;

    }

    private String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token" +
                "?grant_type=client_credential" +
                "&appid=" + WxConfig.APP_ID +
                "&secret=" + WxConfig.secret;

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String responseBody = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(responseBody);

        return jsonObject.getString("access_token");
    }

    public String login2(String username, String password) {
        // 验证码校验
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);

    }
}
